<?php

declare(strict_types=1);

namespace app\api\controller\User;

use app\BaseController;
use app\common\model\Config as ConfigModel;
use app\common\model\Region as RegionModel;
use app\common\model\User\User as UserModel;
use app\common\validate\User\User as UserValiDate;

class Auth extends BaseController
{
    // 登录
    public function login()
    {
        $code = $this->request->param('code');
        if (empty($code)) {
            $this->error('授权失败');
        }

        // 调用微信Api通过授权凭证换取openid
        $openid = $this->code2Session($code);
        if (empty($openid)) {
            $this->error('获取临时登录凭证失败');
        }

        $User = UserModel::where(['openid' => $openid])->find();

        if (!$User) {
            $this->error('请先绑定账号', 'url');
        }
        // 返回微信用户数据
        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'wxAvatar_cdn' => $User['wxAvatar_cdn'],
            'wxAvatar' => $User['wxAvatar'],
            'wxNickname' => $User['wxNickname'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'region_text' => $User['region_text'],
            'region' => $User['region']
        ];
        $this->success('授权成功', null, $data);
    }
    // 绑定
    public function bind()
    {
        $params = $this->request->param();
        if (empty($params['code'])) {
            $this->error('授权失败');
        }
        // 调用微信Api通过授权凭证换取openid
        $openid = $this->code2Session($params['code']);
        if (empty($openid)) {
            $this->error('获取临时登录凭证失败');
        }
        $User = UserModel::where(['email' => $params['email']])->find();
        if ($User) {
            $password = md5($params['password'] . $User['salt']);
            if ($password != $User['password']) {
                $this->error('密码错误');
            }
            $User->openid = $openid;
            $result = $User->save();
            if ($result !== FALSE) {
                $this->success('绑定成功');
            } else {
                $this->error('绑定失败');
            }
        } else {
            $this->error('该邮箱未注册，是否立即注册？', '1');
        }
    }
    // 注册
    public function register()
    {
        try {
            $params = $this->request->param();

            if (empty($params['code'])) {
                throw new \Exception('授权失败');
            }
            // 调用微信Api通过授权凭证换取openid
            $openid = $this->code2Session($params['code']);
            if (empty($openid)) {
                throw new \Exception('获取临时登录凭证失败');
            }
            $salt = build_ranstr();
            $password = md5($params['password'] . $salt);
            // 查询注册积分
            $point = ConfigModel::where(['key' => 'RegisterPoint'])->value('value');
            $data = [
                'email' => $params['email'],
                'password' => $password,
                'salt' => $salt,
                'point' => $point,
                'sex' => 0,
                'auth' => 0,
                'vip' => 1,
                'openid' => $openid
            ];
            // 验证数据 scene('register')=>场景验证
            validate(UserValiDate::class)->scene('weixin')->check($data);
            // 插入数据表
            $result = UserModel::create($data);
            if ($result == false) {
                throw new \Exception('注册失败');
            }
        } catch (\think\exception\ValidateException $e) {
            $this->error($e->getMessage());
        } catch (\Exception $error) {
            $this->error($error->getMessage());
        }
        $this->success('注册成功');
    }
    // 修改资料
    public function profile()
    {
        $params = $this->request->param();
        try {
            $User = UserModel::find($params['userid']);
            if (!$User) {
                throw new \Exception('用户不存在');
            }
            $data = [
                'nickname' => $params['nickname'],
                'sex' => $params['sex'],
                'content' => $params['content']
            ];
            if (!empty($params['code'])) {
                // 查询完整的地区代码
                $parentpath = RegionModel::where(['code' => $params['code']])->value('parentpath');
                // 判断地区是否存在
                if (!$parentpath) {
                    throw new \Exception('所选地区不存在');
                }
                // 转为数组
                [$province, $city, $district] = explode(',', $parentpath);
                $data['province'] = $province;
                $data['city'] = $city;
                // 追加到数组
                $data['district'] = $district;
            }
            // 提交的数据是否存在封面
            if (isset($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
                // 调用上传操作
                $cover = upload('cover');
                // 判断上传是否成功
                if ($cover['code'] === 0) {
                    throw new \Exception($cover['msg']);
                }
                // 封装到数组
                $data['cover'] = $cover['data'];
            }
            $result = UserModel::update($data, ['id' => $User['id']]);
            if ($result === FALSE) {
                if (!empty($data['cover']) && $_FILES['cover']['size'] > 0) {
                    @is_file('./' . (string)$data['cover']) && @unlink('./' . $data['cover']);
                }
                throw new \Exception('修改资料失败');
            } else {
                if (!empty($data['cover']) && $_FILES['cover']['size'] > 0) {
                    @is_file('./' . (string)$User['cover']) && @unlink('./' . $User['cover']);
                }
                $user = UserModel::find($params['userid']);

                $Data = [
                    'id' => $user['id'],
                    'email' => $user['email'],
                    'nickname' => $user['nickname'],
                    'avatar' => $user['avatar_cdn'],
                    'cover' => $user['cover_cdn'],
                    'wxAvatar_cdn' => $User['wxAvatar_cdn'],
                    'wxAvatar' => $user['wxAvatar'],
                    'wxNickname' => $user['wxNickname'],
                    'sex' => $user['sex'],
                    'sex_text' => $user['sex_text'],
                    'province' => $user['province'],
                    'city' => $user['city'],
                    'district' => $user['district'],
                    'createtime' => $user['createtime'],
                    'content' => $user['content'],
                    'point' => $user['point'],
                    'vip' => $user['vip'],
                    'auth' => $user['auth'],
                    'region_text' => $user['region_text'],
                    'region' => $user['region']
                ];
            }
        } catch (\Exception $error) {
            $this->error($error->getMessage());
        }
        $this->success('更新成功', null, $Data);
    }
    public function avatar()
    {
        $userid = $this->request->param('userid');
        $User = UserModel::find($userid);
        if (!$User) {
            $this->error('用户不存在');
        }
        // 是否存在头像
        if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
            // 调用上传操作
            $avatar = upload('avatar');
            // 判断上传是否成功
            if ($avatar['code'] === 0) {
                $this->error($avatar['msg']);
            }
            $result = UserModel::update(['wxAvatar'=>$avatar['data']],['id'=>$userid]);
            if ($result === FALSE) {
                if (!empty($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file('./' . (string)$avatar['data']) && @unlink('./' . $avatar['data']);
                }
                $this->error('修改资料失败');
            } else {
                if (!empty($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file('./' . (string)$User['wxAvatar']) && @unlink('./' . $User['wxAvatar']);
                }
                $user = UserModel::find($userid);
                $Data = [
                    'id' => $user['id'],
                    'email' => $user['email'],
                    'nickname' => $user['nickname'],
                    'avatar' => $user['avatar_cdn'],
                    'cover' => $user['cover_cdn'],
                    'wxAvatar_cdn' => $User['wxAvatar_cdn'],
                    'wxAvatar' => $user['wxAvatar'],
                    'wxNickname' => $user['wxNickname'],
                    'sex' => $user['sex'],
                    'sex_text' => $user['sex_text'],
                    'province' => $user['province'],
                    'city' => $user['city'],
                    'district' => $user['district'],
                    'createtime' => $user['createtime'],
                    'content' => $user['content'],
                    'point' => $user['point'],
                    'vip' => $user['vip'],
                    'auth' => $user['auth'],
                    'region_text' => $user['region_text'],
                    'region' => $user['region']
                ];
                $this->success('修改头像成功',null,$Data);
            }
        }
    }
    protected function code2Session($code)
    {
        $appid = ConfigModel::where(['key' => 'Appid'])->value('value');

        $AppSecret = ConfigModel::where(['key' => 'AppSecret'])->value('value');

        $ApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$AppSecret}&js_code={$code}&grant_type=authorization_code";

        $result = $this->https_request($ApiUrl);
        $data = json_decode($result, true);

        if (!empty($data['openid'])) {
            return $data['openid'];
        } else {
            return FALSE;
        }
    }

    protected function https_request($url, $data = null)
    {
        if (function_exists('curl_init')) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        } else {
            return false;
        }
    }
}
